package com.hx.utils;


import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.spire.doc.documents.ImageType;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;

/**
 * 测试可以用 license 也可以用比较好--sucess
 * word转pdf工具类
 *
 * @author shmily
 */
@Slf4j
public class Word2PdfUtil {

    /**
     * 许可证字符串(可以放到resource下的xml文件中也可)
     */
    private static final String LICENSE = "<License>" +
            "<Data>" +
            "<Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products>" +
            "<EditionType>Enterprise</EditionType>" +
            "<SubscriptionExpiry>20991231</SubscriptionExpiry>" +
            "<LicenseExpiry>20991231</LicenseExpiry>" +
            "<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>" +
            "</Data>" +
            "<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>" +
            "</License>";


    /**
     * 设置 license 去除水印
     */
    private static void setLicense() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(LICENSE.getBytes());
        License license = new License();
        try {
            license.setLicense(byteArrayInputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * word 转 pdf 生成至指定路径，pdf为空则上传至word同级目录
     *
     * @param wordPath word文件路径
     * @param pdfPath  pdf文件路径
     */
    public static void wordConvertPdfFile(String wordPath, String pdfPath) {
        FileOutputStream fileOutputStream = null;
        try {
            pdfPath = pdfPath == null ? getPdfFilePath(wordPath) : pdfPath;
            setLicense();
            File file = new File(pdfPath);
            fileOutputStream = new FileOutputStream(file);
            Document doc = new Document(wordPath);
            doc.save(fileOutputStream, SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fileOutputStream != null;
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) throws IOException {
        String wordPath = "D:\\work\\project\\jar\\wordtopdf-server\\wordtopdfByjdk16\\src\\main\\resources\\target1.docx";
        String destPath = "D:\\work\\project\\jar\\wordtopdf-server\\wordtopdfByjdk16\\src\\main\\resources\\targetA.docx";
        String picturePath = convertSuffix(wordPath, ".png");
//        wordToImage(wordPath,"png");
//        FileInputStream fis = new FileInputStream(new File(wordPath));
//        XWPFDocument document = new XWPFDocument(new FileInputStream(new File(wordPath)));
//        insertImage(document, picturePath);
//        FileOutputStream outStream = new FileOutputStream(destPath);
//        document.write(outStream);


        BufferedImage bufferedImage = new BufferedImage(793, 1122, BufferedImage.TYPE_INT_RGB);
        BufferedImage coverImage = ImageUtils.getCoverImage(bufferedImage);
//        Graphics2D g = bufferedImage.createGraphics();
//
//        g.drawLine(3,3,50,50);//在(3,3)与(50,50)之间画一条线段
//        g.drawString("hello world",60,60);
//
        File outputfile  = new File(picturePath);
        ImageIO.write(coverImage, "png", outputfile);

    }

    public static void wordToImage(String wordPath,String imageType) throws IOException {
        com.spire.doc.Document doc = new com.spire.doc.Document();
        doc.loadFromFile(wordPath);
        BufferedImage bufferedImage = doc.saveToImages(0, ImageType.Bitmap);
        ImageIO.write(bufferedImage, imageType, new FileOutputStream(new File(convertSuffix(wordPath, ".".concat(imageType)))));
        log.info("word转换图片成功！");
    }

    /**
     * word 转 pdf 生成byte字节流
     *
     * @param wordPath word所在的目录地址
     * @return
     */
    public static byte[] wordConvertImage(String wordPath) {
        ByteArrayOutputStream fileOutputStream = null;
        try {
            setLicense();
            fileOutputStream = new ByteArrayOutputStream();
            Document doc = new Document(wordPath);
            doc.save(fileOutputStream, SaveFormat.PDF);
            return fileOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fileOutputStream != null;
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    /**
     * word 转 pdf 生成byte字节流
     *
     * @param wordPath word所在的目录地址
     * @return
     */
    public static byte[] wordConvertPdfByte(String wordPath) {
        ByteArrayOutputStream fileOutputStream = null;
        try {
            setLicense();
            fileOutputStream = new ByteArrayOutputStream();
            Document doc = new Document(wordPath);
            doc.save(fileOutputStream, SaveFormat.PDF);
            return fileOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fileOutputStream != null;
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    private static String convertSuffix(String wordPath, String suffix) {
        int lastIndexOfPoint = wordPath.lastIndexOf(".");
        String pdfFilePath = "";
        if (lastIndexOfPoint > -1) {
            pdfFilePath = wordPath.substring(0, lastIndexOfPoint);
        }
        return pdfFilePath.concat(suffix);
    }

    /**
     * 获取 生成的 pdf 文件路径，默认与源文件同一目录
     *
     * @param wordPath word文件
     * @return 生成的 pdf 文件
     */
    private static String getPdfFilePath(String wordPath) {
        int lastIndexOfPoint = wordPath.lastIndexOf(".");
        String pdfFilePath = "";
        if (lastIndexOfPoint > -1) {
            pdfFilePath = wordPath.substring(0, lastIndexOfPoint);
        }
        return pdfFilePath + ".pdf";
    }

    private static void insertImage(XWPFDocument document, String path) {
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            CTP ctp = paragraph.getCTP();
            for (int dwI = 0; dwI < ctp.sizeOfBookmarkStartArray(); dwI++) {
                try {
                    CTBookmark bookmark = ctp.getBookmarkStartArray(dwI);
                    if (!"celue".equalsIgnoreCase(bookmark.getName())) continue;
                    FileInputStream fis = new FileInputStream(new File(path));
                    XWPFRun run = paragraph.createRun();
                    //bus.png为鼠标在word里选择图片时，图片显示的名字，宽度，高度100，100则为像素单元，根据实际需要的大小进行调整即可。
                    run.addPicture(fis, XWPFDocument.PICTURE_TYPE_JPEG, "target1.jpg", Units.toEMU(400), Units.toEMU(500));
                } catch (InvalidFormatException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }



}
